package 设计模式.责任链模式;

/**
 * 责任链模式
 * 一个处理需要嵌套调用多个类的方法来执行
 *  T -> 需要处理的对象
 *
 * @author luokexiong
 * @version 1.0 2021/1/26
 * @since 2.0.0
 */
public abstract class ProcessingObject<T> {
    public static void main(String[] args) {
        // p1为链头
        ProcessingObject<String> p1 = new HeaderTextProcessing();
        ProcessingObject<String> p2 = new SpellCheckerProcessing();
        p1.setProcess(p2);
        String result = p1.handle("Aren't labdas really sexy?!!");
        System.out.println(result);
    }

    protected ProcessingObject<T> successor;

    public void  setProcess(ProcessingObject<T> successor) {
        this.successor = successor;
    }

    /**
     * 处理方法(递归)
     *
     * @param input 输入
     * @return 处理结果
     */
    public T handle(T input){
        T result = handleWork(input);
        if (null != successor){
            // 若调用链存在则继续执行
            successor.handle(result);
        }
        return result;
    }

    /**
     * 仅允许处理类继承实现
     *
     * @param input 输入
     * @return 输出处理结果
     */
    abstract protected T handleWork(T input);
}

class HeaderTextProcessing extends ProcessingObject<String> {
    public String handleWork(String text){
        return "From Raoul, Mario and Alan: " + text;
    }
}

class SpellCheckerProcessing extends ProcessingObject<String> {
    public String handleWork(String text){
        return text.replaceAll("labda", "lambda");
    }
}
